﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Runtime.InteropServices;

namespace WindowsColor
{
    public partial class ColorForm : Form
    {
        public ColorForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 浏览文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "打开";
            openFileDialog.InitialDirectory = "c:\\";//注意这里写路径时要用c:\\而不是c:\
            openFileDialog.Filter = "jpg(*.jpg)|*.jpg|gif(*.gif)|*.gif|bmp(*.bmp)|*.bmp|png(*.png)|*.png|tif(*.tif)|*.tif";
            //openFileDialog.RestoreDirectory = true;
            //openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtColor.Text = openFileDialog.FileName;

                //File fileOpen = new File(fName);
                //isFileHaveName = true;
                //richTextBox1.Text = fileOpen.ReadFile();
                //richTextBox1.AppendText("");
                GetPhoto(openFileDialog.FileName);
            }
        }
        //显示图片
        private void GetPhoto(string path)
        {
            Image img = Image.FromFile(@path);//双引号里是图片的路径    
            pbxOldphoto.Image = img;
            pbxOldphoto.SizeMode = PictureBoxSizeMode.Zoom;
        }
        /// <summary>
        /// 弹出错误信息
        /// </summary>
        /// <param name="message"></param>
        public static void ShowError(string message)
        {
            MessageBox.Show(message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public bool isnumeric(string str)
        {
            string Value = str;
            if (Value.Substring(0, 1) == "-")
                Value = Value.Substring(1);

            char[] ch = new char[Value.Length];
            ch = Value.ToCharArray();
            for (int i = 0; i < ch.Length; i++)
            {
                if (ch[i] < 48 || ch[i] > 57)
                    return false;
            }
            return true;
        }

        /// <summary>
        /// 调整颜色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnControl_Click(object sender, EventArgs e)
        {
            if (pbxOldphoto.Image == null)
            {
                ShowError("请先选择图片！");
                return;
            }
            if (txtRed.Text == "")
                txtRed.Text = "0";
            if (txtGreed.Text == "")
                txtGreed.Text = "0";
            if (txtBlue.Text == "")
                txtBlue.Text = "0";
            if (isnumeric(txtRed.Text))
            {
                if (int.Parse(txtRed.Text) < -255 || int.Parse(txtRed.Text) > 255)
                {
                    ShowError("Red 颜色值为-255至255之间的整数！");
                    return;
                }
            }
            else
            {
                ShowError("Red 颜色值为-255至255之间的整数！");
                return;
            }

            if (isnumeric(txtGreed.Text))
            {
                if (int.Parse(txtGreed.Text) < -255 || int.Parse(txtGreed.Text) > 255)
                {
                    ShowError("Greed 颜色值为-255至255之间的整数！");
                    return;
                }
            }
            else
            {
                ShowError("Greed 颜色值为-255至255之间的整数！");
                return;
            }

            if (isnumeric(txtBlue.Text))
            {
                if (int.Parse(txtBlue.Text) < -255 || int.Parse(txtBlue.Text) > 255)
                {
                    ShowError("Blue 颜色值为-255至255之间的整数！");
                    return;
                }
            }
            else
            {
                ShowError("Blue 颜色值为-255至255之间的整数！");
                return;
            }

            string path = txtColor.Text;
            System.Drawing.Image image;
            if (path != "")
                image = System.Drawing.Image.FromFile(@path);
            else
                image = pbxOldphoto.Image;



            //var img = Image.FromFile(path);
            //int count = img.GetFrameCount(FrameDimension.Page);
            //img.SelectActiveFrame(FrameDimension.Page, 0);
            //img.Save(, ImageFormat.Png);


            //Image img = Image.FromFile(@path);
            //Guid guid = (Guid)img.FrameDimensionsList.GetValue(0);
            //FrameDimension dimension = new FrameDimension(guid);
            //int totalPage = img.GetFrameCount(dimension);

            ////this.statusBar1.Text = "共"+totalPage+"页"; 

            //for (int i = 0; i < totalPage; i++)
            //{
            //    img.SelectActiveFrame(dimension, i);

            //    img.Save(@"C:\Users\Administrator\Desktop\食为天招牌\" + i + ".gif", System.Drawing.Imaging.ImageFormat.Gif);
            //} 



            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image);

            btnControl.Enabled = false;
            //Dictionary<System.Drawing.Color, PixelColor> _ColorDict = new Dictionary<System.Drawing.Color, PixelColor>();
            int Width = bitmap.Width;
            int Height = bitmap.Height;
            int Red = Convert.ToInt32(txtRed.Text.ToString());
            int Greed = Convert.ToInt32(txtGreed.Text.ToString());
            int Blue = Convert.ToInt32(txtBlue.Text.ToString());
            bitmap = ToGray(bitmap, Red, Greed, Blue);//方法
                                                      //for (int x = 0; x < Width; x++)
                                                      //{
                                                      //    for (int y = 0; y < Height; y++)
                                                      //    {


            //        System.Drawing.Color pixelColor = bitmap.GetPixel(x, y);

            //        int NewRed = 0;
            //        int NewGreen = 0;
            //        int NewBlue = 0;
            //        //像素点颜色的 Alpha 值
            //        byte alpha = pixelColor.A;

            //        //颜色的 RED 分量值
            //        byte red = pixelColor.R;

            //        if ((red + Convert.ToInt32(txtRed.Text.ToString()) > 255))
            //            NewRed = 255;
            //        else if ((red + Convert.ToInt32(txtRed.Text.ToString()) < 0))
            //            NewRed = 0;
            //        else
            //            NewRed = red + Convert.ToInt32(txtRed.Text.ToString());



            //        //颜色的 GREEN 分量值
            //        byte green = pixelColor.G;

            //        if ((green + Convert.ToInt32(txtGreed.Text.ToString()) > 255))
            //            NewGreen = 255;
            //        else if ((green + Convert.ToInt32(txtGreed.Text.ToString()) < 0))
            //            NewGreen = 0;
            //        else NewGreen = green + Convert.ToInt32(txtGreed.Text.ToString());


            //        //颜色的 BLUE 分量值
            //        byte blue = pixelColor.B;
            //        if ((blue + Convert.ToInt32(txtBlue.Text.ToString()) > 255))
            //            NewBlue = 255;
            //        else if ((blue + Convert.ToInt32(txtBlue.Text.ToString()) < 0))
            //            NewBlue = 0;
            //        else
            //            NewBlue = blue + Convert.ToInt32(txtBlue.Text.ToString());

            //        System.Drawing.Color NewColor = Color.FromArgb(red, NewGreen, NewBlue);

            //        //设置像素
            //        bitmap.SetPixel(x, y, NewColor);
            //    }
            //}
            //bitmap.Save(@"C:\Users\Administrator\Desktop\网球方格3.jpg", ImageFormat.Jpeg);
            string ImgType = "";
            if (path != "")
                ImgType = path.Substring(path.LastIndexOf('.'));
            else
                ImgType = pbxOldphoto.Image.RawFormat.ToString();

            pbxNewphoto.Image = Bitmap2Image(bitmap, GetEnum(ImgType));
            pbxNewphoto.SizeMode = PictureBoxSizeMode.Zoom;
            btnControl.Enabled = true;
        }
        public static unsafe Bitmap ToGray(Bitmap img, int Red, int Green, int Blue)
        {
            BitmapData data = img.LockBits(new Rectangle(0, 0, img.Width, img.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            //循环处理 
            //int Width = img.Width;
            //int Height = img.Height;
            //Bitmap bitmap = new Bitmap(Width, Height, PixelFormat.Format32bppRgb);
            //BitmapData newData = img.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);

            unsafe
            {
                // IntPtr ptr = data.Scan0;
                byte* ptr1 = (byte*)(data.Scan0);

                for (int i = 0; i < data.Height; i++)
                {
                    for (int j = 0; j < data.Width; j++)
                    {

                        int NewRed = 0;
                        int NewGreen = 0;
                        int NewBlue = 0;



                        // Declare an array to hold the bytes of the bitmap. 
                        //int bytes = data.Stride * img.Height;
                        //byte[] rgbValues = new byte[bytes];

                        //// Copy the RGB values into the array. 
                        //System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

                        // Set every red value to 255.  
                        //for (int counter = 0; counter < rgbValues.Length; counter += 3)
                        //{
                        //    NewRed =  rgbValues[counter];
                        //    NewGreen =  rgbValues[counter];
                        //    NewBlue = rgbValues[counter];
                        //}

                        NewBlue = ptr1[0];
                        NewGreen = ptr1[1];
                        NewRed = ptr1[2];


                        if ((NewRed + Red) > 255)
                            NewRed = 255;
                        else if ((NewRed + Red) < 0)
                            NewRed = 0;
                        else
                            NewRed = NewRed + Red;

                        if ((NewGreen + Green) > 255)
                            NewGreen = 255;
                        else if ((NewGreen + Green) < 0)
                            NewGreen = 0;
                        else
                            NewGreen = NewGreen + Green;


                        if ((NewBlue + Blue) > 255)
                            NewBlue = 255;
                        else if ((NewBlue + Blue) < 0)
                            NewBlue = 0;
                        else
                            NewBlue = NewBlue + Blue;




                        ptr1[0] = Convert.ToByte(NewBlue);
                        ptr1[1] = Convert.ToByte(NewGreen);
                        ptr1[2] = Convert.ToByte(NewRed);

                        // Copy the RGB values back to the bitmap 
                        //System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);

                        // Unlock the bits. 
                        //img.UnlockBits(data); 
                        //img.UnlockBits(data);


                        ptr1 += 3;

                    }

                }
                img.UnlockBits(data);

            }
            return img;
        }
        /// <summary>
        /// 转换成图片
        /// </summary>
        /// <param name="Bi"></param>
        /// <returns></returns>
        private static Image Bitmap2Image(System.Drawing.Bitmap Bi, System.Drawing.Imaging.ImageFormat ImgType)
        {
            MemoryStream ms = new MemoryStream();
            Bi.Save(ms, ImgType);

            using (System.IO.MemoryStream Newms = new System.IO.MemoryStream(ms.ToArray()))
            {
                System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
                ms.Flush();
                return returnImage;
            }

        }

        public System.Drawing.Imaging.ImageFormat GetEnum(string value)
        {
            // openFileDialog.Filter = "jpg(*.jpg)|*.jpg|jpeg|*.jpeg|gif(*.gif)|*.gif|bmp(*.bmp)|*.bmp|png(*.png)|*.png|tiff(*.tiff)|*.tiff";
            System.Drawing.Imaging.ImageFormat ImgType;
            switch (value)
            {
                case "jpg":
                    ImgType = System.Drawing.Imaging.ImageFormat.Jpeg;
                    break;
                case "gif":
                    ImgType = System.Drawing.Imaging.ImageFormat.Gif;
                    break;
                case "bmp":
                    ImgType = System.Drawing.Imaging.ImageFormat.Bmp;
                    break;
                case "png":
                    ImgType = System.Drawing.Imaging.ImageFormat.Png;
                    break;
                case "tif":
                    ImgType = System.Drawing.Imaging.ImageFormat.Tiff;
                    break;
                default:
                    ImgType = System.Drawing.Imaging.ImageFormat.Jpeg;
                    break;
            }
            return ImgType;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (pbxOldphoto.Image == null)
            {
                ShowError("请先选择图片！");
                return;
            }
            if (pbxNewphoto.Image == null)
            {
                ShowError("请先预览图片！");
                return;
            }
            SaveFileDialog SaveFile = new SaveFileDialog();
            SaveFile.Title = "保存";
            SaveFile.InitialDirectory = "c:\\";//注意这里写路径时要用c:\\而不是c:\
            SaveFile.Filter = "jpg(*.jpg)|*.jpg|gif(*.gif)|*.gif|bmp(*.bmp)|*.bmp|png(*.png)|*.png|tif(*.tif)|*.tif";
            SaveFile.RestoreDirectory = true;
            if (pbxNewphoto.Image == null)
            {
                MessageBox.Show("没有预览图片！", "提示：", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (SaveFile.ShowDialog() == DialogResult.OK)
            {
                string localFilePath = SaveFile.FileName.ToString(); //获得文件路径 
                string fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1); //获取文件名，不带路径
                string Type = fileNameExt.Substring(fileNameExt.LastIndexOf('.'));
                pbxNewphoto.Image.Save(localFilePath, GetEnum(Type));
                txtAddress.Text = localFilePath;
            }
        }

        private void ColorForm_Load(object sender, EventArgs e)
        {

            pbxOldphoto.SizeMode = PictureBoxSizeMode.Zoom;
        }
    }
}
